'''list列表groupBy分组使用

Python list列表groupby分组用法
注意分组之前应先使用分组字段先排好序
'''

from itertools import groupby

user_list = [
    {"uid": 1, "sex": "男", "age": 10},
    {"uid": 3, "sex": "男", "age": 20},
    {"uid": 4, "sex": "女", "age": 20},
    {"uid": 4, "sex": "女", "age": 31},
    {"uid": 2, "sex": "男", "age": 10}
]
# 多字段分组
user_sort = sorted(user_list, key=lambda x: (x["sex"], x["age"]))
# 多字段分组
user_group = groupby(user_sort, key=lambda x: (x["sex"], x["age"]))
for key, group in user_group:
    print(key, list(group))


print("自定义分组key")


# 自定义分组key
def g(x):
    if (x['age'] > 0) and (x['age'] <= 10):
        return 'small'
    elif (x['age'] > 10) and (x['age'] <= 20):
        return 'mid'
    else:
        return 'max'


user_sort = sorted(user_list, key=lambda x: x["age"])
user_group = groupby(user_sort, key=g)
for key, group in user_group:
    print(key, list(group))

# 执行结果如下：
'''
('女', 20) [{'uid': 4, 'sex': '女', 'age': 20}]
('女', 31) [{'uid': 4, 'sex': '女', 'age': 31}]
('男', 10) [{'uid': 1, 'sex': '男', 'age': 10}, {'uid': 2, 'sex': '男', 'age': 10}]
('男', 20) [{'uid': 3, 'sex': '男', 'age': 20}]
自定义分组key
small [{'uid': 1, 'sex': '男', 'age': 10}, {'uid': 2, 'sex': '男', 'age': 10}]
mid [{'uid': 3, 'sex': '男', 'age': 20}, {'uid': 4, 'sex': '女', 'age': 20}]
max [{'uid': 4, 'sex': '女', 'age': 31}]
'''

import itertools

a_list = [("Animal", "cat"),
          ("Animal", "dog"),
          ("Bird", "peacock"),
          ("Bird", "pigeon")]

an_iterator = itertools.groupby(a_list, lambda x: x[0])

for key, group in an_iterator:
    key_and_group = {key: list(group)}
    print(key_and_group)

# 输出
'''
{'Animal':[('Animal', 'cat'), ('Animal', 'dog')]}
{'Bird':[('Bird', 'peacock'), ('Bird', 'pigeon')]}
'''